package com.lorizz.picpub.web.controller.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.ui.Model;

import com.lorizz.index.Indexer;
import com.lorizz.index.Request;
import com.lorizz.index.Result;
import com.lorizz.index.impl.RequestImpl;
import com.lorizz.picpub.web.controller.SearchController;
import com.lorizz.upm.Image;
import com.lorizz.upm.np.ImageNP;
import com.lorizz.upm.np.NPUtils;

public class SearchControllerImpl implements SearchController {

	private Indexer<Image> imageIndexer;

	public void setImageIndexer(Indexer<Image> imageIndexer) {
		this.imageIndexer = imageIndexer;
	}

	@Override
	public String search(Model model) {
		model.addAttribute("search", "");
		return "search";
	}

	@Override
	public String search(String searchString, Model model) {
		Request request = new RequestImpl(searchString);
		Result<Image> result = imageIndexer.search(request);
		List<Image> images = result.getItems();
		List<ImageNP> imageNPs = new ArrayList<ImageNP>();
		for (Image image : images) {
			ImageNP imageNP = NPUtils.packageImage(image);
			imageNP.getImageVariants().addAll(NPUtils.packageImageVariantList(image.getImageVariants()));
			imageNPs.add(imageNP);
		}
		model.addAttribute("images", imageNPs);
		model.addAttribute("search", searchString);
		return "search";
	}

}
